var app = getApp();
let isclick = true;
Component({
  properties: {
    prop_goods_info: {
      type: null, //父组件的商品详情数据
    },
    // 属性值可以在组件使用时指定
    goodsId: {
      type: Number,
    },
    goodsType: {
      type: String,
    },
    xqBoxShow: {
      type: null,
    },
    ipnonexbol: {
      type: null,
    },
    activityid: {
      type: null,
    },
    enterAt: {
      type: Object,
    },
    // 拼团store_id
    store_id: {
      type: null,
    },
    // 拼团
    fight_groups: {
      type: null,
    },
    datop: {
      type:null,
    },
  },
  data: {
    first_content: null,
    goods_plugin: {}, //插件plugin的数据
    goods_info: {}, //data全部的数据或者get_goods的数据
    goodsInfo: "", //get_goods的数据或者goods_info的数据
    gooddatas: "", // data全部的数据
    language: "",

    //动态模糊框
    popupModeshow: true,
    //限时购开关
    isBuy: false,

    //是否门店拼团
    is_o2o: false,
    favorite: false,

    // 初始评论页数
    commentPage: 1,
    // 是否有更多评论
    noMoreComment: false,
    //海报显隐
    posterShow: false,
    posterImg: "",

    //more
    isLoadMore: true,
    page: 1,
    total_page: 0,
    roomdataBol: false,
    roomdata: [],
    min_micro: [],
    tabList: [], //微贴和直播
    show1: false,
    iPnoneBottomBol: false,

    skuImages: [],
    showSkuImages: false,
    activeSkuIndex: 0,
    activeSkuIndex_1: null, //用于关闭时保存点击预览前的序号，在预览关闭时重新设置预览起始位置
    activeSkuIndex_2: null,

    btnData: {
      over_top: 500,
      icon_url: "https://www.yunzmall.com//min_img/icon-fontclass-zhiding.png"
    },
    // 海报按钮
    btnData2: {
      over_top: 450,
      icon_url: "https://www.yunzmall.com//min_img/bc_eweima.png"
    },

    //打开分享弹窗
    showSahre: false,
    // 是否开启好物圈插件
    wechatcircle_open: 0,

    broadcast_data: [], //飘窗订单数据
    wx_video_link: 0, //视频号扩展插件
    showVideoLink: false,
    article_url: null, // 视频号扩展链接

    //活动是否结束
    ispt: false,
    activeChapter: [''],//课程目录
    isIosSell: false,

    navIdx: 0,
    navList: [{
        id: "list0",
        name: "目录"
      },
      {
        id: "list1",
        name: "介绍"
      },
      {
        id: "list2",
        name: "评价"
      }, {
        id: "list3",
        name: "推荐"
      }
    ],
  },

  lifetimes: {
    attached(e) {
      isclick = true;
      this.getiPnoneBottom();
      let language = wx.getStorageSync("langIndex");
      this.setData({
        language: language.en,
      });
      // 客服初始化
      this.init();
      this.getGoodsPage();  
      this.initTabsData();
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
    ready() {},
  },
  observers:{
    'datop':function(top){
      this.scrollTopFun(top)
    }
  },
  methods: {
    toUrl(e) {
      let _data = e.currentTarget.dataset || {};
      console.log(_data);
      this.wxRouterLink(_data);
    },
    wxRouterLink(_data) {
      let _Param = "";
      const { url, ...otherParam } = _data;
      console.log(otherParam);
      Object.keys(otherParam).forEach(function (key) {
        if (otherParam[key] !== "") _Param += key + "=" + otherParam[key] + "&";
      });
      if (url === "") return;
      wx.navigateTo({
        url: url + "?" + _Param.slice(0, -1),
      });
    },
    contorBuyNow(){},
    // 分享弹窗
    openShare() {
      this.setData({
        showSahre: true,
      });
    },
    // 分享弹窗关闭
    closeSharePop() {
      this.setData({
        showSahre: false,
      });
    },
    //收藏操作
    onFavorite(e) {
      this.data.favorite ? this.removeFavorite() : this.addFavorite();
    },
    //移除收藏
    removeFavorite() {
      let that = this;
      let urlStr = app.getNetAddresss("member.member-favorite.destroy");
      urlStr += "&goods_id=" + this.data.goodsId;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              favorite: false,
            });
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 3000,
            });
          } // else {

          //}
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //添加收藏
    addFavorite() {
      let that = this;
      let urlStr = app.getNetAddresss("member.member-favorite.store");
      urlStr += "&goods_id=" + this.data.goodsId;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              favorite: true,
            });
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 3000,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    // 分享到好物圈
    shareGoods() {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.wechatcircle_products.api.import.import");
      let data = {
        product_list: [{
          item_code: that.data.goodsInfo.id,
          title: that.data.goodsInfo.title,
          desc: that.data.goodsInfo.title,
          category_list: ["商品"],
          image_list: that.data.goodsInfo.thumb_url,
          src_wxapp_path: "packageA/detail_v2/detail_v2?id=" + that.data.goodsInfo.id,
          sku_list: [{
            sku_id: that.data.goodsInfo.id,
            price: that.data.goodsInfo.price,
            original_price: that.data.goodsInfo.market_price,
            status: 1,
          },],
        },],
      };
      if (isclick) {
        isclick = false;
        app._postNetWork({
          url: urlStr,
          data: data,
          success: function (resdata) {
            var res = resdata.data;
            if (res.result == 1) {
              setTimeout(function () {
                isclick = true;
              }, 1000);
              if (wx.openBusinessView) {
                wx.openBusinessView({
                  businessType: "friendGoodsRecommend",
                  extraData: {
                    product: {
                      item_code: that.data.goodsInfo.id,
                      title: that.data.goodsInfo.title,
                      image_list: that.data.goodsInfo.thumb_url,
                    },
                  },
                  success: function (res) {
                    that.setData({
                      showSahre: false,
                    });
                  },
                  fail: function (res) {
                    console.log("fail", res);
                    that.setData({
                      showSahre: false,
                    });
                  },
                });
              } else {
                wx.showToast({
                  title: "微信7.0.3及以上版本支持 请先更新微信版本",
                  icon: "none",
                  duration: 3000,
                });
              }
            } else {
              wx.showToast({
                title: res.msg,
                icon: "none",
                duration: 3000,
              });
            }
          },
          fail: function (res) {
            setTimeout(function () {
              isclick = true;
            }, 1000);
            console.log(res);
          },
        });
      }
    },
    // 获取手机型号
    getiPnoneBottom() {
      let value = wx.getStorageSync("iPhoneBottom");
      if (value) {
        this.setData({
          iPnoneBottomBol: true,
        });
      }
    },
    // 客服
    init() {
      this.setData({
        wechatcircle_open: 0,
        show1: false,
        service_QRcode: "",
        service_mobile: "",
      });
    },
    // 客服
    callPhone() {
      wx.makePhoneCall({
        phoneNumber: this.data.service_mobile,
      });
    },
    // 客服关闭
    closePop() {
      this.setData({
        show1: false,
      });
    },

    toGroupCode() {
      if(this.data.goods_plugin.group_code.jump_mode === 'home') {
        wx.reLaunch({
          url: '/packageE/groupCode/groupCode',
        });
      }else if(this.data.goods_plugin.group_code.code_mini_url){
        wx.navigateTo({
          url: this.data.goods_plugin.group_code.code_mini_url
        });
      }
    },

    // 服务标签弹窗开启
    showCan(e) {
      this.setData({
        popupModeshow: e.detail
      });
    },

    //品牌跳转
    toBrandDetail(e) {
      var brandval = e.currentTarget.dataset.brandval;
      wx.navigateTo({
        url: "/packageB/member/goods/GoodsBrand/GoodsBrand?id=" + brandval,
      });
    },

    //设置选择后的数据
    setDataByTabIndex() {
      //获取评论
      this.getCommentData();
    },
    //获取评论数据
    getCommentData() {
      let that = this;
      let urlStr = app.getNetAddresss("goods.comment.get-comment");
      urlStr += "&goods_id=" + this.data.goodsId;
      urlStr += "&page=" + this.data.commentPage;
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.data.length < 20) {
              that.setData({
                noMoreComment: true,
              });
            }
            that.setData({
              commentPage: that.data.commentPage + 1,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },

    //海报生成
    postShow(e) {
      console.log(e);
      this.setData({
        posterShow: true,
        showSahre: false,
      });
    },
    posterClose() {
      this.setData({
        posterShow: false,
      });
    },
    saveImg() {
      wx.getSetting({
        success(res) {
          if (!res.authSetting["scope.writePhotosAlbum"]) {
            wx.authorize({
              scope: "scope.writePhotosAlbum",
              success() {
                console.log("授权成功");
              },
            });
          }
        },
      });
      var imgSrc = this.data.posterImg.image_url;
      wx.downloadFile({
        url: imgSrc,
        success: function (res) {
          console.log(res);
          //图片保存到本地
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function (data) {
              wx.showToast({
                title: "保存成功",
                icon: "none",
                duration: 3000,
              });
            },
            fail: function (err) {
              console.log(err);
              if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                console.log("当初用户拒绝，再次发起授权");
                wx.openSetting({
                  success(settingdata) {
                    if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                      wx.showToast({
                        icon: "none",
                        title: "获取权限成功,再次长按保存图片",
                        duration: 3000,
                      });
                    } else {
                      wx.showToast({
                        icon: "none",
                        title: "获取权限失败,保存图片需要用户授权",
                        duration: 3000,
                      });
                    }
                  },
                });
              }
            },
            complete(res) {
              console.log(res);
            },
          });
        },
      });
    },

    //直播间跳转
    gopage(e) {
      let status = e.currentTarget.dataset.status;
      let id = e.currentTarget.dataset.id;
      let backid = e.currentTarget.dataset.backid;
      if (status == 1) {
        wx.navigateTo({
          url: "/packageD/directSeeding/livePage/livePage?id=" + id + "&playerType=live",
        });
      } else if (status == 2) {
        wx.navigateTo({
          url: "/packageD/directSeeding/livePage/livePage?id=" + id + "&playerType=video" + "&backid=" + backid,
        });
      } else if (status == 3) {
        wx.navigateTo({
          url: "/packageD/directSeeding/foreshow/foreshow?id=" + id,
        });
      }
    },
    // 获取直播间列表
    getLiveList() {
      let urlStr = app.getNetAddresss("goods.goods.get-room");
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          page: this.data.page,
          goods_id: this.data.goodsId,
        },
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            let list = [];
            for(let i=0;i<res.data.data.length;) {
              list.push(res.data.data.slice(i, i + 2));
              i += 2;
            }
            this.setData({
              total_page: res.data.last_page,
              roomdata: list,
              roomdataBol: true,
            });
            if(this.data.roomdata.length > 0) {
              this.setData({
                tabList: this.data.tabList.concat([{id: 2,name: '直播间'}])
              });
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 3000,
            });
          }
        },
        fail: (res)=> {
          console.log(res.msg);
        },
      });
    },
    _getMoreData() {
      let that = this;
      let urlStr = app.getNetAddresss("goods.goods.get-room");
      that.data.isLoadMore = false; // 防止多次请求分页数据
      if (this.data.page >= this.data.total_page) {
        return;
      } else {
        this.data.page = this.data.page + 1;
        app._postNetWork({
          url: urlStr,
          showToastIn: false,
          data: {
            page: this.data.page,
            goods_id: this.data.goodsId,
          },
          success: function (resdata) {
            var res = resdata.data;
            if (res.result == 1) {
              that.setData({
                isLoadMore: true,
                roomdata: that.data.roomdata.concat(res.data.data),
              });
            } else {
              that.setData({
                page: that.data.page - 1,
                isLoadMore: false,
              });
            }
          },
          fail: function (res) {
            console.log(res.msg);
          },
        });
      }
    },
    // 获取直播间列表end
    reachBottom() {
      if (this.data.roomdataBol) {
        if (this.data.isLoadMore) {
          this._getMoreData();
        } else {
          console.log("没有更多数据");
        }
      }
    },

    handleMicro(index, maxLength, micro_communities) {
      let img_list = [];
      for(let i=0;i<micro_communities.list.length; i++) {
        if(micro_communities.list[i].has_many_image && micro_communities.list[i].has_many_image[index]) {
          img_list.push(micro_communities.list[i].has_many_image[index]);
        }
      }
      this.setData({
        min_micro: this.data.min_micro.concat(img_list)
      });
      if(index < maxLength && this.data.min_micro.length < 12) {
        index++;
        this.handleMicro(index, maxLength, micro_communities);
      }
    },
    getGoodsPage() {
      let data = this.data.prop_goods_info;
      // data全部数据
      if (data.plugin) {

        if (data.plugin.micro_communities) {
          // 微社区帖子
          let num_list = [];
          for(let i=0;i<data.plugin.micro_communities.list.length; i++) {
            num_list.push(data.plugin.micro_communities.list[i].has_many_image.length);
          }

          //计算最长的图片数组长度   不断递归整合到this.min_micro
          let maxLength = Math.max(...num_list);
          let index = 0;

          this.handleMicro(index, maxLength - 1, data.plugin.micro_communities);

          // this.min_micro再重新分成6张一组
          let list = [];
          for(let i=0;i<this.data.min_micro.length;) {
            list.push(this.data.min_micro.slice(i, i + 6));
            i += 6;
          }
          if(list.length > 0) {
            this.data.tabList.push({id: 1,name: '关联微贴'});
          }

          this.setData({
            min_micro: list,
            tabList: this.data.tabList
          });
        }
        if (data.plugin.is_room && data.plugin.is_room == 1) {
          this.getLiveList();
        }
        if (data.plugin.wechatcircle_open && data.plugin.wechatcircle_open == 1) {
          this.setData({
            wechatcircle_open: 1,
          });
        }

        if(data.plugin && data.plugin.project_template) {
          this.data.tabList.push({id: 3,name: '知识库'});
          this.setData({
            knowledgeList: data.plugin.project_template.list,//供应链知识库
            tabList: this.data.tabList
          });
        }

      }
      let resSteam = wx.getSystemInfoSync();
      let isIosSell = resSteam.platform == 'ios'?true:false;

      let basic_info = wx.getStorageSync("yz_basic_info");
      let plugin_setting = basic_info.plugin_setting;
      

      this.setData({
        broadcast_data: data.plugin?.broadcast_data?data.plugin?.broadcast_data:[],
        favorite: data.is_favorite ? (data.is_favorite.status == 1 ? true : false) : false,
        goods_plugin: data.plugin || {},
        courseId:data.plugin?.course_supply?.chapter[0]?.course_id,
        sectionId:data.plugin?.course_supply?.chapter[0]?.section[0]?.section_id,
        videoId:data.plugin?.course_supply?.chapter[0]?.chapter_id,
        goods_info: data,
        gooddatas: data,
        isIosSell: isIosSell,
        plugin_setting: plugin_setting,
        service_QRcode: data.customer_service.service_QRcode,
        service_mobile: data.customer_service.service_mobile,
        cservice: data.customer_service.cservice,
        first_content: data.get_goods.content
      });
      console.log(this.data.plugin_setting.yz_course_supply.is_ios_sell && isIosSell);
      this.getData(data.get_goods);
      if (data.plugin && data.plugin.wx_video_link) {
        this.setData({
          wx_video_link: data.plugin.wx_video_link,
        });
      }
    },
    //获取数据
    getData(data) {
      // get_goods数据
      if (Number(data.market_price) == 0) {
        data.notMarket_price = 0;
      } else {
        data.notMarket_price = 1;
      }
      this.setData({
        goodsInfo: data,
        xqBoxShow:data.detail_show?true:false
      });
      // 分享的自定义图片
      wx.setStorageSync("GoddsShareImg", data.thumb);
      if (this.data.goodsInfo.member_discount) {
        if (app._isTextEmpty(this.data.goodsInfo.member_discount.discount)) {
          this.setData({
            openVip: 1,
          });
        } else {
          this.setData({
            openVip: this.data.goodsInfo.member_discount.discount,
          });
        }
      }

      this.setDataByTabIndex(); //设置商品详情
    },
  
    // 视频拓展链接
    getVideoLink() {
      wx.showLoading({
        title: "正在生成中...",
      });
      // 生成视频号链接
      let that = this;
      let urlStr = app.getNetAddresss("plugin.wx-video-link.frontend.index.index");
      urlStr += "&id=" + this.properties.goodsId;
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.article_url == "" || res.data.article_url == null || res.data.article_url == undefined) {
              setTimeout(() => {
                that.getVideoLink();
              }, 3000);
            } else {
              that.setData({
                article_url: res.data.article_url,
                showVideoLink: true,
                showSahre: false,
              });
              setTimeout(function () {
                wx.hideLoading();
              }, 800);
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 3000,
            });
          }
        },
        fail: function (res) {},
      });
    },
    // 复制链接
    onCopy() {
      wx.setClipboardData({
        data: this.data.article_url,
        success(res) {
          wx.showToast({
            title: "复制成功",
            icon: "none",
            duration: 3000,
          });
        },
        fail() {
          wx.showToast({
            title: "复制失败",
            icon: "none",
            duration: 3000,
          });
        },
      });
      this.setData({
        showVideoLink: false,
        article_url: "",
      });
    },

    // 控制海报显示
    selfShowPop() {
      this.setData({
        show1: true,
      });
    },
    onChapterChange(event) {
      this.setData({
        activeChapter: event.detail,
      });
    },
    toOrder(){
      wx.navigateTo({
        url:"/packageD/buy/myOrder_v2/myOrder_v2?tag=-2" + "&goodsId=" + this.properties.goodsId + "&optionsId=" + this.data.goodsInfo.has_many_options[0].id + "&total=1"
      });
    },

    initTabsData(){
      // 页面被展示
      let query = wx.createSelectorQuery().in(this);
      let heightArr = [];
      query.selectAll('.navListView').boundingClientRect((react) => {
        react.forEach((res) => {
          heightArr.push(res.top)
        })
        this.setData({
          anchorArray: heightArr
        });
      }).exec(); //导航栏吸顶
    },
    scrollTopFun: function (e) {
      // let scrollTop=e.detail.scrollTop;
      let scrollTop=e;
      let scrollArr= this.data.anchorArray;
      if(!scrollArr) return
      if(scrollTop>=scrollArr[scrollArr.length-1]){
        return;
      }else {
        for(let i=0;i<scrollArr.length;i++){
          if(scrollTop>=0&&scrollTop<scrollArr[0]){
            // navIdx控制筛选块高亮显示
            this.setData({
              navIdx: 0
            });
          }else if(scrollTop>=scrollArr[i-1]&&scrollTop<scrollArr[i]) {
            this.setData({
              navIdx: i
            });
          }
        }
      }
    },
    //点击锚点导航栏
    clickScroll: function (e) {
      wx.pageScrollTo({
        scrollTop: this.data.anchorArray[e.target.dataset.idx]-60,
        duration: 300,
      });
      this.setData({
        navIdx: e.target.dataset.idx
      });
    },
    sectionOn(e){
      let {cantry,courseid,sectionid,index} = e.currentTarget.dataset;
      let chapter = this.data.goods_plugin?.course_supply?.chapter[index];
      let chapterId = this.data.goods_plugin.course_supply.id;
      if(cantry == 0  && this.data.goods_plugin.course_supply.is_buy == 0) {
        return app.tips('请先购买课程');
      }
      wx.navigateTo({
        url:`/packageF/course/chapterList/chapterList?chapterid=${chapterId}&courseid=${courseid}&sectionid=${sectionid}&videoid=${chapter.chapter_id}` //补充参数
      })
    }
  },
});
